package org.example.kunkun_filter.controller;

import org.example.kunkun_filter.config.WechatConfig;
import org.example.kunkun_filter.dao.ApiResponse;
import org.example.kunkun_filter.dao.LoginRequest;
import org.example.kunkun_filter.dao.LoginResponse;
import org.example.kunkun_filter.dao.WechatLoginResponse;
import org.example.kunkun_filter.service.LoginService;
import org.example.kunkun_filter.utils.JwtTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

@RestController
@RequestMapping("/auth")
public class AuthController {

    @Autowired
    private WechatConfig wechatConfig;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private LoginService loginService;

    @PostMapping("/wechat-login")
    public ResponseEntity<ApiResponse<LoginResponse>> wechatLogin(@RequestBody LoginRequest loginRequest) {
        try {
            // 1. 使用code获取openid和session_key
            String url = wechatConfig.getApi().getJscode2session() +
                    "?appid=" + wechatConfig.getAppid() +
                    "&secret=" + wechatConfig.getSecret() +
                    "&js_code=" + loginRequest.getCode() +
                    "&grant_type=authorization_code";
    
            // 修改：先获取字符串响应
            String responseStr = restTemplate.getForObject(url, String.class);
            // 使用FastJSON解析字符串为WechatLoginResponse对象
            WechatLoginResponse wechatResponse = com.alibaba.fastjson.JSON.parseObject(responseStr, WechatLoginResponse.class);
    
            if (wechatResponse == null || !wechatResponse.isSuccess()) {
                return ResponseEntity.badRequest().body(
                        (ApiResponse<LoginResponse>) ApiResponse.error("微信登录失败: " +
                                (wechatResponse != null ? wechatResponse.getErrmsg() : "未知错误"))
                );
            }
    
            // 2. 生成JWT token
            String token = jwtTokenUtil.generateToken(wechatResponse.getOpenid());
    
            // 3. 创建用户信息并检查是否已存在
            LoginResponse.User user = new LoginResponse.User();
            user.setOpenid(wechatResponse.getOpenid());
            user.setNickname("微信用户");
            user.setAvatarUrl("");
            user.setIdentity(2);
            user.setDownloadCount(0);
    
            // 调用service并获取用户信息（可能是新用户或现有用户）
            loginService.registerUser(user);
    
            // 4. 构建响应 - 只返回token和过期时间，不返回用户信息
            LoginResponse loginResponse = new LoginResponse();
            loginResponse.setToken(token);
            loginResponse.setExpiresIn(7200L);
    
            return ResponseEntity.ok(ApiResponse.success("登录成功", loginResponse));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body((ApiResponse<LoginResponse>) ApiResponse.error("服务器错误: " + e.getMessage()));
        }
    }

    @GetMapping("/check-token")
    public ResponseEntity<ApiResponse<?>> checkToken(@RequestHeader("Authorization") String authHeader) {
        if (authHeader == null || !authHeader.startsWith("Bearer ")) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                    .body(ApiResponse.error("未提供有效的认证令牌"));
        }

        String token = authHeader.substring(7);
        if (jwtTokenUtil.validateToken(token)) {
            return ResponseEntity.ok(ApiResponse.success("令牌有效", null));
        } else {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                    .body(ApiResponse.error("令牌无效或已过期"));
        }
    }

    // token刷新接口
    @PostMapping("/refresh-token")
    public ResponseEntity<ApiResponse<LoginResponse>> refreshToken(@RequestHeader("Authorization") String authHeader) {
        try {
            if (authHeader == null || !authHeader.startsWith("Bearer ")) {
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                        .body((ApiResponse<LoginResponse>) ApiResponse.error("未提供有效的认证令牌"));
            }

            String token = authHeader.substring(7);
            String newToken = jwtTokenUtil.refreshToken(token);

            if (newToken != null) {
                // 构建响应
                LoginResponse loginResponse = new LoginResponse();
                loginResponse.setToken(newToken);
                loginResponse.setExpiresIn(7200L);

                return ResponseEntity.ok(ApiResponse.success("令牌刷新成功", loginResponse));
            } else {
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                        .body((ApiResponse<LoginResponse>) ApiResponse.error("令牌无效，需要重新登录"));
            }
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body((ApiResponse<LoginResponse>) ApiResponse.error("刷新令牌失败: " + e.getMessage()));
        }
    }
}
